package com.xbkj.ui_design;

import static com.xbkj.ui_design.R.id.home;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.SparseArray;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.xbkj.ui_design.databinding.ActivityMainBinding;
import com.xbkj.ui_design.fragment.DiscoveryFragment;
import com.xbkj.ui_design.fragment.HomeFragment;
import com.xbkj.ui_design.fragment.MeFragment;
import com.xbkj.ui_design.fragment.MessageFragment;

public class MainActivity extends AppCompatActivity {

    private com.xbkj.ui_design.databinding.ActivityMainBinding binding;

    // 使用SparseArray缓存Fragment实例
    private SparseArray<Fragment> fragmentCache = new SparseArray<>(4);

    private int currentTabId = home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        // 在 Activity 中初始化
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        // 隐藏状态栏和导航栏
//        insetsController.hide(WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.navigationBars());
        // 设置状态栏文字为浅色（适配深色背景）
//        insetsController.setAppearanceLightStatusBars(false);
        // 恢复已存在的Fragment
        if (savedInstanceState != null) {
            restoreFragments(savedInstanceState);
        } else {
            initFirstFragment();
        }
        initListener();
    }

    private void initFirstFragment() {
        Fragment homeFragment = new HomeFragment();
        fragmentCache.put(home, homeFragment);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.nav_host_fragment, homeFragment)
                .commit();
    }

    private void restoreFragments(Bundle savedInstanceState) {
        // 从FragmentManager恢复已有实例
        fragmentCache.put(home, findFragment(home));
        fragmentCache.put(R.id.discovery, findFragment(R.id.discovery));
        fragmentCache.put(R.id.message, findFragment(R.id.message));
        fragmentCache.put(R.id.me, findFragment(R.id.me));
        currentTabId = savedInstanceState.getInt("CURRENT_TAB", home);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        showNewFragment(currentTabId,transaction);
        transaction.commitNowAllowingStateLoss();
    }

    private Fragment findFragment(int tabId) {
        return getSupportFragmentManager().findFragmentByTag(getFragmentTag(tabId));
    }

    private void hideCurrentFragment(FragmentTransaction transaction) {
        Fragment currentFragment = fragmentCache.get(currentTabId);
        if (currentFragment != null) {
            transaction.hide(currentFragment);
        }
    }

    private void showNewFragment(int tabId, FragmentTransaction transaction) {
        Fragment fragment = fragmentCache.get(tabId);
        if (fragment == null) {
            fragment = createFragment(tabId);
            fragmentCache.put(tabId, fragment);
            transaction.add(R.id.nav_host_fragment, fragment, getFragmentTag(tabId));
        } else {
            transaction.show(fragment);
        }
    }

    private void switchTab(int newTabId) {
        if (newTabId == currentTabId) return;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideCurrentFragment(transaction);
        showNewFragment(newTabId, transaction);
        transaction.commitNowAllowingStateLoss();
        currentTabId = newTabId;
    }

    @SuppressLint("NonConstantResourceId")
    private Fragment createFragment(int tabId) {
        if (tabId == R.id.home){
            return HomeFragment.newInstance();
        }else if (tabId == R.id.discovery){
            return DiscoveryFragment.newInstance();
        }else if (tabId == R.id.message){
            return MessageFragment.newInstance();
        }else if (tabId == R.id.me){
            return MeFragment.newInstance();
        }
        throw new IllegalArgumentException("Invalid tab ID");
    }

    private String getFragmentTag(int tabId) {
        return "TAB_" + tabId;
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("CURRENT_TAB", currentTabId);
    }

    private void initListener() {
        binding.home.setOnClickListener(v -> switchTab(v.getId()));
        binding.discovery.setOnClickListener(v -> switchTab(v.getId()));
        binding.message.setOnClickListener(v -> switchTab(v.getId()));
        binding.me.setOnClickListener(v -> switchTab(v.getId()));
    }
}